package com.qf.smsplatform.search.service.impl;

import com.qf.smsplatform.common.index.StandardReport;
import com.qf.smsplatform.common.index.StandardSubmit;
import com.qf.smsplatform.search.service.SearchService;
import com.qf.smsplatform.search.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 作者：郝国栋
 * 项目名：IntelliJ IDEA
 * 时间:2020/8/30  20:31
 * 描述:
 */
@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    @Resource
    RestHighLevelClient client;

    private final String INDEX = "sms_submit_log_";

    private final String TYPE = "sms_submit_log_type";

    @Override
    public void add(StandardSubmit submit) throws IOException {

        String yyyy = new SimpleDateFormat("yyyy").format(new Date());
        // 创建request对象
        IndexRequest request = new IndexRequest(INDEX + yyyy, TYPE, submit.getSequenceId());

        // 封装request对象信息
        request.source(JsonUtils.object2Map(submit));
        // 通过client发送请求到es
        IndexResponse resp = client.index(request, RequestOptions.DEFAULT);
        // 获取返回结果
        if(!"CREATED".equalsIgnoreCase(resp.getResult().toString()) && !"UPDATED".equalsIgnoreCase(resp.getResult().toString())){
            log.error("【搜索模块】 添加数据失败  index = {},type = {},submit = {}",INDEX,TYPE,submit);
            // 抛自己声明的异常.
            throw new RuntimeException("【搜索模块】 添加数据失败");
        }
    }

    @Override
    public void update(StandardReport report) throws IOException {
        //1. request
        String yyyy = new SimpleDateFormat("yyyy").format(new Date());
        UpdateRequest request = new UpdateRequest(INDEX + yyyy,TYPE,report.getSequenceId());
        //2. 封装 , 修改的内容
        int state = report.getState();
        Map<String,Object> doc = new HashMap<>();
        doc.put("reportState",state);
        request.doc(doc);
        //3. 发送
        UpdateResponse resp = client.update(request, RequestOptions.DEFAULT);
        //4. 判断resp
        if(!"UPDATED".equals(resp.getResult().toString())){
            log.error("【搜索模块】 添加数据失败  index = {},type = {},doc = {}",INDEX,TYPE,doc);
            // 抛自己声明的异常.
            throw new RuntimeException("【搜索模块】 修改数据失败");
        }
    }
}
